package com.nwcl.common.utils;

import com.aliyun.oss.OSSClient;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.UUID;

/**
 * @author liguiqin
 * @date 2023/5/25
 */
@Component
public class OssUtil {
    private static String ENDPOINT = "";                  //内网
    private static String GET_ENDPOINT = "";               //外网
    private static String ACCESS_KEY_ID = "";
    private static String ACCESS_KEY_SECRET = "";
    public static String BUCKET_NAME = "";
    private static Logger log = LogManager.getLogger(OssUtil.class);

    @Value("${aliyun.oss.endpoint}")
    public void setENDPOINT(String ENDPOINT) {
        OssUtil.ENDPOINT = ENDPOINT;
    }

    @Value("${aliyun.oss.getendpoint}")
    public void setGETENDPOINT(String GETENDPOINT) {
        OssUtil.GET_ENDPOINT = GETENDPOINT;
    }

    @Value("${aliyun.oss.access_key_id}")
    public void setAccessKeyId(String accessKeyId) {
        OssUtil.ACCESS_KEY_ID = accessKeyId;
    }

    @Value("${aliyun.oss.access_key_secret}")
    public void setAccessKeySecret(String accessKeySecret) {
        OssUtil.ACCESS_KEY_SECRET = accessKeySecret;
    }

    @Value("${aliyun.oss.bucket.name}")
    public void setBucketName(String bucketName) {
        OssUtil.BUCKET_NAME = bucketName;
    }


    /*
     * @Description: 上传文件到阿里云
     * @Author liguiqin
     * @Date 2023/5/31 10:01
     * @param: file 文件
     * @param: folder   文件夹
     * @param: extName  文件后缀名
     * @return java.lang.String
     * @UpdateDate 2023/5/31 10:01
     **/
    public static String privateUploadFile(MultipartFile file, String folder, String extName) {
        OSSClient ossClient = null;
        try {
            String fileName = UUID.randomUUID().toString().replaceAll("-", "") + "." + extName;
            // 上传文件流。
            String uploadFolder = folder + "/" + fileName;
            ossClient = new OSSClient(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
            ossClient.putObject(BUCKET_NAME, uploadFolder, file.getInputStream());
            // 关闭OSSClient。
            ossClient.shutdown();
            return uploadFolder;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    /*
     * @Description:传文件流到阿里云
     * @Author liguiqin
     * @Date 2023/5/31 10:00
     * @param: inputStream 文件流
     * @param: folder 文件夹
     * @param: extName  文件后缀名
     * @return java.lang.String
     * @UpdateDate 2023/5/31 10:00
     **/
    public static String privateUploadFile(InputStream inputStream, String folder, String extName) {
        OSSClient ossClient = null;
        try {
            String fileName = UUID.randomUUID().toString().replaceAll("-", "") + "." + extName;
            // 上传文件流。
            String uploadFolder = folder + "/" + fileName;
            ossClient = new OSSClient(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
            ossClient.putObject(BUCKET_NAME, uploadFolder, inputStream);
            // 关闭OSSClient。
            ossClient.shutdown();
            return uploadFolder;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    /*
     * @Description:  获取阿里云文件的可直接访问url
     * @Author liguiqin
     * @Date 2023/5/31 9:59
     * @param: fileName 文件名
     * @param: expireTime 过期时间 为空则默认为1小时
     * @return java.lang.String
     * @UpdateDate 2023/5/31 9:59
     **/
    public static String getOssUrl(String fileName, Long expireTime) {
        //非阿里云的文件直接返回
        if (fileName.startsWith("https") || fileName.startsWith("http")) {
            return fileName;
        }
        long currentTimeMillis = System.currentTimeMillis();
        expireTime = null == expireTime || currentTimeMillis >= expireTime ? currentTimeMillis + 3600 * 1000 : expireTime;
        // 设置URL过期时间。
        Date expiration = new Date(expireTime);
        // 生成以GET方法访问的签名URL，访客可以直接通过浏览器访问相关内容。
        OSSClient ossClient = new OSSClient(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        URL url = ossClient.generatePresignedUrl(BUCKET_NAME, fileName, expiration);
        try {
            ossClient.shutdown();
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        String urls = url.toString();
        urls = getHttpsUrl(urls);
        return urls;
    }


    private static String getHttpsUrl(String url) {
        if (url.startsWith("https")) {
            return url;
        }
        if (url.startsWith("http")) {
            url = url.replaceFirst("http", "https");
        }
        return url;
    }

    public static void main(String[] args) throws Exception {
        String localhostFileName = "D:\\test.txt";
        FileInputStream fileInputStream = new FileInputStream(localhostFileName);
        String fileName = privateUploadFile(fileInputStream, "test", "txt");
        System.out.println("path:" + fileName);
        System.out.println("fullPath:" + getOssUrl(fileName, null));
    }

}
